package cn.bs.controller;


import cn.bs.constant.Constants;
import cn.bs.domain.dao.*;
import cn.bs.domain.dto.CommentDTO;
import cn.bs.domain.dto.PostDTO;
import cn.bs.domain.dto.ReviewDTO;
import cn.bs.domain.pojo.CommentPOJO;
import cn.bs.domain.pojo.Result;
import cn.bs.domain.vo.PostInfoVO;
import cn.bs.domain.vo.PostVO;
import cn.bs.domain.vo.ReviewVO;
import cn.bs.mapper.*;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.Resource;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.*;

@RestController
@RequestMapping("/community")
public class CommunityController {

    @Autowired
    private ReviewMapper reviewMapper;

    @Autowired
    private PostMapper postMapper;

    @Autowired
    private CommentMapper commentMapper;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private LikeMapper likeMapper;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @GetMapping("/getReview")//对餐厅的评价
    public Result getReview(Integer canteenId) {
        List<Review> reviews =reviewMapper.getReviewByCanteenId(canteenId);

        List<ReviewVO> reviewsVO = new ArrayList<>();

        for (Review review : reviews) {
            if (review == null){
                break;
            }
            ReviewVO vo = new ReviewVO();
            vo.setId(review.getId());
            User user = userMapper.getById(review.getUserId());
            vo.setUserName(user.getName());
            vo.setContent(review.getContent());
            vo.setImage(review.getImage());
            vo.setDate(review.getDate());
            reviewsVO.add(vo);
        }

        return Result.ok(reviewsVO);
    }

    @PostMapping("/addReview")
    public Result addReview( HttpServletRequest request,
                             @RequestParam("canteenId") Integer canteenId,
                             @RequestParam("content") String content,
                             @RequestParam(value = "image", required = false) MultipartFile image){

        System.out.println("发布评论");
        System.out.println("Received canteenId: " + canteenId);
        System.out.println("Received content: " + content);
        if (image != null) {
            System.out.println("Received file name: " + image.getOriginalFilename());
        } else {
            System.out.println("No file received.");
        }

        Integer userId = Integer.valueOf(stringRedisTemplate
                .opsForValue().get(request.getHeader("Authorization")));

        // 处理文件上传
        String imagePath = null;
        if (image != null && !image.isEmpty()) {
            try {
                String uploadDir = Constants.DOWNLOAD_PATH; // 文件保存路径
                File dir = new File(uploadDir);
                if (!dir.exists()) {
                    dir.mkdirs(); // 创建目录
                }

                // 生成唯一文件名
                String fileName = System.currentTimeMillis() + "_" + image.getOriginalFilename();
                String filePath = Paths.get(uploadDir, fileName).toString();

                // 保存文件
                image.transferTo(new File(filePath));
                imagePath = fileName; // 保存相对路径
            } catch (Exception e) {
                e.printStackTrace();
                return Result.fail("文件上传失败");
            }
        }

        Integer maxId = reviewMapper.getMaxId();

        Review review = new Review();
        review.setId(maxId+1);
        review.setCanteenId(canteenId);
        review.setUserId(userId);
        review.setContent(content);
        review.setImage(imagePath);
        review.setDate(new Date());
        reviewMapper.insert(review);

        return Result.ok("店铺评价发布成功");
    }

    @GetMapping("/getPost")
    public Result getPost(HttpServletRequest request) {
        String header = request.getHeader("Authorization");
        Integer userId = Integer.valueOf(stringRedisTemplate
                .opsForValue().get(header));
        List<Post> posts =postMapper.getPostList();

        List<PostVO> postsVO = new ArrayList<>();

        for (Post post : posts) {
            if (post == null){
                break;
            }
            PostVO vo = new PostVO();
            vo.setId(post.getId());
            User user = userMapper.getById(post.getUserId());
            vo.setUserName(user.getName());
            vo.setTitle(post.getTitle());
            vo.setContent(post.getContent());
            vo.setImage(post.getImage());
            vo.setLikes(post.getLikes());
            vo.setDate(post.getDate());
            if (likeMapper.getByUserIdAndPostId(userId,post.getId()) != null){
                vo.setIsLike(1);
            }else {
                vo.setIsLike(0);
            }
            postsVO.add(vo);
        }

        return Result.ok(postsVO);
    }

    //查看当前用户是否点赞帖子
    @GetMapping("/isLike/{postId}")
    public Result isLike(@PathVariable Integer postId, HttpServletRequest request){
        System.out.println("查看当前用户是否点赞帖子" + postId);
        Integer userId = Integer.valueOf(stringRedisTemplate
                .opsForValue().get(request.getHeader("Authorization")));

        if(userMapper.getById(userId) == null){
            return Result.fail("用户不存在");
        }

        Post post = postMapper.getById(postId);
        if (post == null){
            return Result.fail("美食动态不存在");
        }

        Likes likes = likeMapper.getByUserIdAndPostId(userId,postId);
        if (likes == null){
            return Result.ok("0");
        }else {
            return Result.ok("1");
        }
    }

    //点赞功能
    @PostMapping("/likePost/{postId}")
    public Result likePost(@PathVariable Integer postId, HttpServletRequest request){
        Integer userId = Integer.valueOf(stringRedisTemplate
                .opsForValue().get(request.getHeader("Authorization")));

        if(userMapper.getById(userId) == null){
            return Result.fail("用户不存在");
        }

        Post post = postMapper.getById(postId);
        if (post == null){
            return Result.fail("美食动态不存在");
        }

        Likes likes = likeMapper.getByUserIdAndPostId(userId,postId);

        if (likes == null){
            post.setLikes(post.getLikes()+1);
            postMapper.updateById(post);
            likeMapper.insert(new Likes(null,userId,postId));
            System.out.println("点赞成功");
            return Result.ok("点赞成功");
        }else {
            post.setLikes(post.getLikes()-1);
            postMapper.updateById(post);
            likeMapper.deleteByUserIdAndPostId(userId,postId);
            System.out.println("取消点赞");
            return Result.ok("取消点赞");
        }
    }

    @GetMapping("/getPostById/{postId}")
    public Result getPostById(@PathVariable Integer postId, HttpServletRequest request){
        String header = request.getHeader("Authorization");
        Integer accountId = Integer.valueOf(stringRedisTemplate
                .opsForValue().get(header));
        System.out.println("获取帖子");
        System.out.println(postId);
        Post post =postMapper.getById(postId);

        User user =userMapper.getById(post.getUserId());
        String name = user.getName();



        List<Comment> comments =commentMapper.getCommentByPostId(postId);
        List<CommentPOJO> commentPOJOS = new ArrayList<>();

        for (Comment comment : comments) {
            if (comment == null){
                break;
            }

            CommentPOJO pojo = new CommentPOJO();
            pojo.setId(comment.getId());
            pojo.setUserId(comment.getUserId());
            pojo.setUserName(name);
            pojo.setPostId(comment.getPostId());
            pojo.setContent(comment.getContent());
            pojo.setSonCount(comment.getSonCount());
            pojo.setStatue(comment.getStatus());
            if (comment.getStatus() == 1){
                pojo.setContent("该评论已删除");
            }
            pojo.setDate(comment.getDate());
            commentPOJOS.add(pojo);
        }

        Integer isLike = likeMapper.getByUserIdAndPostId(accountId,postId) == null ? 0 : 1;

        PostInfoVO infoVO = new PostInfoVO(post.getId(), post.getUserId(),name,
                post.getTitle(), post.getContent(),post.getImage(), post.getLikes()
                , post.getDate(), commentPOJOS, isLike);

        return Result.ok(infoVO);
    }

//    @GetMapping("/uploads")
//    public ResponseEntity<byte[]> getImage(@PathVariable String imageName) throws IOException {
//        String imagePath = "E:/image/uploads/" + imageName;
//        File imageFile = new File(imagePath);
//
//        if (!imageFile.exists()) {
//            return ResponseEntity.notFound().build();
//        }
//        Resource resource = new FileSystemResource(imagePath);
//        System.out.println(imagePath);
//        // 读取文件并转换为 Base64 字符串
//        // 检查图片是否存在
//        if (!resource.exists() || !resource.isReadable()) {
//            return ResponseEntity.status(404).body(null);
//        }
//
//        // 读取图片为字节数组
//        byte[] imageBytes = Files.readAllBytes(Path.of(imagePath));
//
//        // 返回图片数据
//        return ResponseEntity.ok()
//                .contentType(MediaType.IMAGE_JPEG) // 根据图片类型设置 MediaType
//                .body(imageBytes);
//    }

    @GetMapping("/getCommentByFather")
    public Result getCommentByFather(@RequestParam Integer fatherId) {
        List<Comment> comments =commentMapper.getCommentByFather(fatherId);

        List<CommentPOJO> commentPOJOS = new ArrayList<>();

        for (Comment comment : comments) {
            if (comment == null){
                break;
            }
            CommentPOJO pojo = new CommentPOJO();
            pojo.setId(comment.getId());
            pojo.setUserId(comment.getUserId());
            pojo.setUserName(userMapper.getById(comment.getUserId()).getName());
            pojo.setPostId(comment.getPostId());
            pojo.setContent(comment.getContent());
            pojo.setSonCount(comment.getSonCount());
            pojo.setDate(comment.getDate());
            commentPOJOS.add(pojo);
        }
        return Result.ok(commentPOJOS);
    }


    @PostMapping("/addPost")
    public Result addPost(HttpServletRequest request,@RequestPart("title") String title,
                          @RequestPart("content") String content,
                          @RequestPart(value = "file", required = false) MultipartFile file){

        System.out.println("发布帖子");
        System.out.println("title:" + title);
        System.out.println("content:" + content);
        System.out.println(file);
        System.out.println();
        System.out.println();
        System.out.println();
        System.out.println();
        System.out.println();

        if(title == null || content == null){
            return Result.fail("标题或内容不能为空");
        }


        Integer userId = Integer.valueOf(stringRedisTemplate
                .opsForValue().get(request.getHeader("Authorization")));


        // 处理文件上传
        String imagePath = null;
        if (file != null && !file.isEmpty()) {
            try {
                String uploadDir = Constants.DOWNLOAD_PATH; // 文件保存路径
                File dir = new File(uploadDir);
                if (!dir.exists()) {
                    dir.mkdirs(); // 创建目录
                }

                // 生成唯一文件名
                String fileName = System.currentTimeMillis() + "_" + file.getOriginalFilename();
                String filePath = Paths.get(uploadDir, fileName).toString();

                // 保存文件
                file.transferTo(new File(filePath));
                imagePath = fileName; // 保存相对路径
            } catch (Exception e) {
                e.printStackTrace();
                return Result.fail("文件上传失败");
            }
        }


        // 创建帖子对象
        Post post = new Post();
        post.setId(postMapper.getMaxId() + 1);
        post.setUserId(userId);
        post.setTitle(title);
        post.setContent(content);
        post.setImage(imagePath); // 保存文件路径
        post.setDate(new Date());
        postMapper.insert(post);

        return Result.ok("发布成功");
    }


    @PostMapping("/addComment")
    public Result addComment(@RequestBody CommentDTO commentDTO, HttpServletRequest request) {
        Integer userId = Integer.valueOf(stringRedisTemplate
                .opsForValue().get(request.getHeader("Authorization")));

        Integer fatherId = commentDTO.getFatherId();

        Comment fatherComment = commentMapper.getById(fatherId);
        if (fatherId == null || fatherComment == null) {
            fatherId = 0;
        }else if (!Objects.equals(fatherComment.getPostId(), commentDTO.getPostId())){
            return Result.fail("页面错误");
        }

        Comment comment = new Comment();
        comment.setId(commentMapper.getMaxId() + 1);
        comment.setUserId(userId);
        comment.setPostId(commentDTO.getPostId());
        comment.setFatherId(fatherId);
        comment.setContent(commentDTO.getContent());
        comment.setDate(new Date());

        commentMapper.insert(comment);

        return Result.ok("发布成功");
    }


}
